﻿using PhotoGallery.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace PhotoGallery.Data.Repository
{
    public class PhotoRepository : BaseRepository
    {
        //const string 
        //    PhotoFolder = "images",
        //    EmptyPhotoImage = "empty_image.png";

        private XDocument doc;
        string path;
        Album album;
        private List<Photo> photos;

        public PhotoRepository(Album currentAlbum, string owner)
        {
            Owner = owner;
            album = currentAlbum;
            string albumFolder = getAlbumFolder(album);
            LoadData(album.ID, albumFolder,false);
        }


        public PhotoRepository(int albumID, string owner, string albumFolder)
        {
            Owner = owner;
            LoadData(albumID, albumFolder,false);
        }

        public IEnumerable<Photo> Get()
        {
            return photos;
        }

        public Photo Get(int id)
        {
            return photos.FirstOrDefault(m => m.ID == id);
        }

        public void Create(Photo photo)
        {
            photo.ID = GetMaxValue() + 1;
            photo.UploadedOn = DateTime.UtcNow;

            photos.Add(photo);
            doc.Root.Add(new XElement("image",
                              new XElement("id", photo.ID),
                              new XElement("title", photo.Title),
                              new XElement("filename", photo.FileName),
                              new XElement("description", photo.Description),
                              new XElement("uploadedOn", ConvertDate(photo.UploadedOn)),
                              new XElement("modifiedOn", null),
                              new XElement("deletedOn", null),
                              new XElement("shared", (int)photo.Shared),
                              new XElement("orderNumber", GetMaxOrderNumber()+1),
                              new XElement("active",true)
                              ));

            doc.Save(path + "ImageMetaData.xml");

            if (String.IsNullOrEmpty(album.FileName))
            {
                AlbumRepository albumRepo = new AlbumRepository(Owner);
                albumRepo.Update(album);
            }
        }

        public void Update(Photo image)
        {
            image.ModifiedOn = DateTime.UtcNow;
            XElement node = doc.Root.Elements("image").Where(i => (int)i.Element("id") == image.ID).FirstOrDefault();
            
            node.SetElementValue("id", image.ID);
            node.SetElementValue("title", image.Title ?? "");
            node.SetElementValue("filename", image.FileName );
            node.SetElementValue("description", image.Description ?? "");
            node.SetElementValue("modifiedOn", ConvertDate(image.ModifiedOn));
            node.SetElementValue("shared", (int)image.Shared);
            
            doc.Save(path + Settings.PhotoMetaDataXml);
        }

        public void Delete(Photo image)
        {
            image.DeletedOn = DateTime.UtcNow;
            XElement node = doc.Root.Elements("image").Where(i => (int)i.Element("id") == image.ID).FirstOrDefault();

            node.SetElementValue("deletedOn", ConvertDate(image.DeletedOn));
            node.SetElementValue("active", false);

            doc.Save(path + Settings.PhotoMetaDataXml);
        }

        public void Erise(int id)
        {
            Photo image = photos.FirstOrDefault(i => i.ID == id);
            
            doc.Root.Elements("image").Where(i => (int)i.Element("id") == id).Remove();
            doc.Save(path + "ImageMetaData.xml");
        }

        #region privateMethods

        private int GetMaxValue()
        {
            int count = doc.Descendants("image").Count();
            if (count > 0)
            {
                var maxID = (from prod in doc.Descendants("image")
                             select
                             (
                                         int.Parse(prod.Element("id").Value)
                             )).Max();
                return maxID;
            }
            else
            {
                return 0;
            }
        }

        private int GetMaxOrderNumber()
        {
            int count = doc.Descendants("image").Count();
            if (count > 0)
            {
                var maxID = (from prod in doc.Descendants("image")
                             select
                             (
                                         int.Parse(prod.Element("orderNumber").Value)
                             )).Max();
                return maxID;
            }
            else
            {
                return 0;
            }
        }

        private void LoadData(int albumID, string albumFolder = "", bool loadAlbums = true)
        {
            photos = new List<Photo>();
            string albumUrl = "/Images/";
            //if (loadAlbums)
            //{
            //    //album = new AlbumRepository(Owner).Get(albumID);
            //    path = BasePath + Settings.UploadsFolder + Owner + "\\Photos\\" + getAlbumFolder(album);
            //    albumUrl = "/Images/" + getAlbumUrl(album);
            //}
            //else
            //{
                path = BasePath + Settings.UploadsFolder + Owner + "\\Photos\\" + albumFolder + "\\";
                albumUrl = "/Images/" + albumFolder + "/";
            //}
            doc = XDocument.Load(path + Settings.PhotoMetaDataXml);
            var qry = from image in doc.Descendants("image")
                      select new Photo(
                                          Convert.ToInt32(image.Element("id").Value),
                                          image.Element("title").Value,
                                          image.Element("filename").Value,
                                          image.Element("description").Value,
                                          ConvertDate(image.Element("uploadedOn").Value),
                                          ConvertDate(image.Element("modifiedOn").Value),
                                          ConvertDate(image.Element("deletedOn").Value),
                                          (SharedAlbum)Enum.Parse(typeof(SharedAlbum), image.Element("shared").Value),
                                          Convert.ToInt32(image.Element("orderNumber").Value),
                                          image.Element("active").Value == "false" ? false : true
                                      );
            photos.AddRange(qry.Where(x => x.Active == true).OrderByDescending(x => x.OrderNumber).ThenByDescending(x=>x.ID).ToList<Photo>());
        }

        #endregion
    }
}